package com.health.tools;

import java.io.IOException;
import java.util.Calendar;
import java.util.Set;

import com.health.NovaApplication;
import com.health.tablebean.BTDevice;
import com.sdses.BtReaderClient;
import com.sdses.Common;
import com.sdses.IClientCallBack;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

/**
 * 神思身份证读卡器对接【如需获取照片等其他信息，需参照demo】
 * 
 * @author nova
 *
 */
public class IDCardTool {
	private static final String TAG2 = "IDCardTool";

	BluetoothAdapter btAdapt;
	public static BluetoothSocket btSocket;
	private Activity activity;
	public boolean isConnected;
	private Bitmap bm;
	public static boolean isConnectSocket = false;

	private boolean bSflxdk = false;// 是否连续读卡
	private boolean bSfdzxdz = false;// 最新地址
	private boolean bSfdzw = false;// （是否显示指纹信息）

	String strName = null;
	String strAddress = null;
	int nNeed = 0;
	byte[] bRecv = new byte[1024];// 1024
	int nRecved = 0;
	private static BtReaderClient mClient;

	byte[] jmmy = new byte[24];

	MediaPlayer m_soundSucess;
	MediaPlayer m_soundError;

	private int iNeedReadCount = 1;

	public IDCardTool(Activity activity) {
		super();
		this.activity = activity;
		initData(activity);
	}

	/**
	 * 初始化数据
	 * 
	 * @param activity
	 * @author 王婷婷
	 * @date 2017年6月15日 上午10:10:25
	 */
	private void initData(Activity activity) {
		btAdapt = BluetoothAdapter.getDefaultAdapter();
		if (btAdapt == null) {
			Toast.makeText(activity.getApplicationContext(), "您的机器上没有发现蓝牙适配器，本程序将不能运行!", Toast.LENGTH_SHORT).show();
		}
		// android.bluetooth.device.action.ACL_CONNECTED
		if (btAdapt.getState() != BluetoothAdapter.STATE_ON) {// 如果蓝牙还没开启

			boolean flag = btAdapt.enable();
			// 开启蓝牙成功还是失败
			if (flag) {
				NovaApplication.isBluetoothOpen = true;
			} else {
				NovaApplication.isBluetoothOpen = false;
			}

		} else if (btAdapt.getState() == BluetoothAdapter.STATE_ON) {
			NovaApplication.isBluetoothOpen = true;
		}

		IntentFilter intent = new IntentFilter();
		intent.addAction(BluetoothDevice.ACTION_FOUND); // 用BroadcastReceiver来取得搜索结果
		intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
		intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		// 注册Receiver来获取蓝牙设备相关的结果
		activity.getApplicationContext().registerReceiver(searchDevices, intent);
	}

	public void unRedisterReceiver() {
		activity.getApplicationContext().unregisterReceiver(searchDevices);
	}

	private BroadcastReceiver searchDevices = new BroadcastReceiver() {

		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(BluetoothDevice.ACTION_FOUND)) { // found device
				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				if (device.getName() == null) {
					Log.w("ComShell", "In BroadcastReceiver device.getName() is null");
					return;

				}
				String str = device.getName() + "|" + device.getAddress();

				if (str.startsWith("SS-") && NovaApplication.fdbmanger
						.findAllBTByWhere(BTDevice.class, "macAddress = " + "'" + device.getAddress() + "'")
						.size() > 0) {
					connect(str);
				}

			} else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)) {
				// btnDis.setText("正在扫描");
				// btnDis.setTextColor(Color.RED);
			} else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
				// btnDis.setText("扫描设备");
				// btnDis.setTextColor(Color.BLACK);
				// Toast.makeText(MainActivity.this, "扫描完成，点击列表中的设备来尝试连接",
				// 3000).show();
			}
		}
	};

	private void addPairedDevice() // 增加配对设备
	{
		Set<BluetoothDevice> pairedDevices = btAdapt.getBondedDevices();
		if (pairedDevices.size() > 0) {
			for (BluetoothDevice device : pairedDevices) {
				String str = device.getName() + "|" + device.getAddress();
				if (str.startsWith("SS-") && NovaApplication.fdbmanger
						.findAllBTByWhere(BTDevice.class, "macAddress = " + "'" + device.getAddress() + "'")
						.size() > 0) {
					try {
						connect(str);
					} catch (Exception e) {
						e.printStackTrace();
					}

				}
			}
		}
	}

	private void connect(String str) {

		// if (btAdapt.getState() != BluetoothAdapter.STATE_ON) {// 如果蓝牙还没开启
		// Toast.makeText(activity.getApplicationContext(), "请开启蓝牙",
		// Toast.LENGTH_SHORT).show();
		// return;
		// }

		if (btAdapt.isDiscovering())
			btAdapt.cancelDiscovery();
		String[] values = str.split("\\|");
		strAddress = values[1];
		Log.w(Common.TAG, values[1]);

		Log.w("eeeeeeeeeee" + Common.TAG, values[1] + "\n" + values[0]);
		try {
			readCard(values[0]);

		} catch (Exception e) {
			Log.w(Common.TAG, "Error connected to: " + strAddress);
			e.printStackTrace();
		}

	}

	public void beginScan() {

		// if (btAdapt.getState() != BluetoothAdapter.STATE_ON) {// 如果蓝牙还没开启
		// Toast.makeText(activity.getApplicationContext(), "请先开启蓝牙",
		// Toast.LENGTH_SHORT).show();
		// return;
		// }

		try {
			if (!btAdapt.isDiscovering()) {
				// addPairedDevice();
				btAdapt.startDiscovery();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void stopScan() {

	}

	public void readCard(String strName) {
		try {
			mClient = NovaApplication.getInstance().getCloientInstance(activity, IDCardTool.this);
			// mClient = new BtReaderClient(activity);
			// mBtState = new ReceiveBtStateData();
			// mClient.setCallBack(mBtState);
			Log.w("ComShell", "strAddress is:" + strAddress);

			startScanReceive();
			Message msg = handler.obtainMessage(110, "");// 发送消息
			handler.sendMessage(msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (btAdapt == null || btAdapt.getState() != BluetoothAdapter.STATE_ON) {
			return;
		}

		try {
			if (mClient != null) {
				isConnected = mClient.connectBt(strAddress);
				Log.w("eeeeeeeeeeeeeeee---isConnected", "" + isConnected);
				if (isConnected) {
					beginReadCard();
				}
			} else {
				// mClient = new BtReaderClient(activity);
				mClient = NovaApplication.getInstance().getCloientInstance(activity, IDCardTool.this);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public class ReceiveBtStateData implements IClientCallBack {

		public void onBtState(final boolean is_connect) {
			if (is_connect == true) {
				isConnectSocket = true;
				// 蓝牙连接成功
				// tvLog.append("蓝牙连接成功..\n");
				// iv.setImageBitmap(null);
				// iv.setVisibility(View.GONE);
			} else if (is_connect == false) {
				isConnectSocket = false;
				Log.e(TAG2, "断开连接");
				stopScanReceive();
				// Toast.makeText(activity, "身份证读卡器蓝牙已断开",
				// Toast.LENGTH_LONG).show();
				// 蓝牙连接失败
				// tvLog.append("蓝牙连接失败...\n");
				// iv.setImageBitmap(null);
				// iv.setVisibility(View.GONE);
			}
		}
	}

	private int readCount = 0;
	private boolean bStopReadCard = false;
	// 按钮事件

	public void beginReadCard() {
		if (mClient != null) {
			readCount = 0;
			new Thread(new GetDataThread()).start();
		}
	}

	long start;

	private class GetDataThread implements Runnable {
		private String data = "";
		private byte[] cardInfo = new byte[256];
		private Message msg;// 主要改了这个地方，好像启作用了
		private String wltPath = "";
		private String termBPath = "";

		public GetDataThread() {
		}

		public void run() {
			boolean bRet = false;
			if (mClient == null) {
				try {
					if (!mClient.bShellOk)
						return;
					Log.w("ComShell", "after  bShellOk");
					// Thread.sleep(2000);//模块上电后需要等待2秒钟 才能正常工作
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				Log.w("ComShell", "mClient not null");
			}
			try {
				readCount = 0;
				while ((!bStopReadCard) && (readCount < iNeedReadCount)) {
					readCount++;
					Log.e("ComShell", "readCount" + readCount);
					Log.e("ComShell", "iNeedReadCount" + iNeedReadCount);
					Log.w("ComShell", "GetDataThread while...");
					start = System.currentTimeMillis();
					msg = handler.obtainMessage(7, data);
					handler.sendMessage(msg);
					bRet = mClient.SearchCard();
					if ((bRet) || (bSflxdk)) {
						msg = handler.obtainMessage(1, data);
						handler.sendMessage(msg);
						bRet = mClient.SelectCard();
						Log.e("ComShell", "if ((bRet) || (bSflxdk)) ");
						if ((bRet) || (bSflxdk)) {
							Log.e("ComShell", "(bRet) || (bSflxdk)");
							if (bSfdzw) {
								// 指纹
								bRet = mClient.ReadCardWithFinger();
							} else {
								bRet = mClient.ReadCard();
							}
							Log.e("ComShell", "bRet" + bRet);
							if (bRet) {
								cardInfo = mClient.GetCardInfoBytes();
								if (bSfdzxdz) {
									byte[] newAddr = new byte[70];
									Thread.sleep(500);
									mClient.ReadNewAddr(newAddr);
									data = String.format("%s,%s,%s,%s,%s,%s,%s,%s-%s", mClient.GetName(cardInfo),
											mClient.GetGender(cardInfo), mClient.GetNational(cardInfo),
											mClient.GetBirthday(cardInfo), mClient.GetAddress(cardInfo),
											mClient.GetIndentityCard(cardInfo), mClient.GetIssued(cardInfo),
											mClient.GetStartDate(cardInfo), mClient.GetEndDate(cardInfo),
											new String(newAddr, "UTF-16LE"));
								} else {
									data = String.format("%s,%s,%s,%s,%s,%s,%s,%s-%s", mClient.GetName(cardInfo),
											mClient.GetGender(cardInfo), mClient.GetNational(cardInfo),
											mClient.GetBirthday(cardInfo), mClient.GetAddress(cardInfo),
											mClient.GetIndentityCard(cardInfo), mClient.GetIssued(cardInfo),
											mClient.GetStartDate(cardInfo), mClient.GetEndDate(cardInfo));

								}
								msg = handler.obtainMessage(333, data);// 自定义数据读取
								handler.sendMessage(msg);

								// msg = handler.obtainMessage(0, data);//
								// 发送读取消息
								// handler.sendMessage(msg);

								// 解析照片数据（暂时不用）
								// wltPath = "/data/data/com.sdses/files/";
								// termBPath = "/mnt/sdcard/";
								// int nret = mClient.GetPic(wltPath,
								// termBPath);
								// if (nret > 0) {
								// Bitmap bm =
								// BitmapFactory.decodeFile("/data/data/com.sdses/files/zp.bmp");
								// msg = handler.obtainMessage(100, bm);// 发送消息
								// handler.sendMessage(msg);
								// } else if (nret == -5) {
								// msg = handler.obtainMessage(101, data);//
								// 发送消息
								// handler.sendMessage(msg);
								// } else if (nret == -1) {
								// msg = handler.obtainMessage(102, data);//
								// 发送消息
								// handler.sendMessage(msg);
								// }
								// break;
							} else {
								Log.w("ComShell", "GetDataThread readCard error 6");
								msg = handler.obtainMessage(6, data);// 发送消息
								handler.sendMessage(msg); // readCard error
							}
						} else {
							Log.w("ComShell", "GetDataThread selectCard error 5");
							msg = handler.obtainMessage(5, data);// 发送消息
							handler.sendMessage(msg); // selectCard error
						}
					} else {
						Log.w("ComShell", "GetDataThread searchCard error 4");
						msg = handler.obtainMessage(4, data);// 发送消息
						handler.sendMessage(msg); // searchCard error
					}
					// Thread.sleep(50);
					Thread.sleep(1500);
				}
				msg = handler.obtainMessage(110, data);// 发送消息
				handler.sendMessage(msg);
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private Handler handler = new Handler() {// 处理UI绘制
		private String data;
		private int t_sec1, t_sec2;
		private int t_msec1, t_msec2;

		private Calendar t;

		@Override
		public void handleMessage(Message msg) {// M_ERROR M_VALIDATE_ERROR
												// I_ERROR I_VALIDATE_ERROR
			switch (msg.what) { // C_ERROR C_VALIDATE_ERROR D_ERROR
								// D_VALIDATE_ERROR
			case 0:
				// 拼接所有数据（如身份证信息、读卡时间、读卡次数、指纹信息等）
				data = (String) msg.obj;
				if (data == null) {
				} else {
					//
					// tvLog.append(data);
					t = Calendar.getInstance();
					t_sec2 = t.get(Calendar.SECOND);
					t_msec2 = t.get(Calendar.MILLISECOND);
					// Log.w("ComShell","t_sec1 is:"+t_sec1+"t_msec1
					// is:"+t_msec1);
					// Log.w("ComShell","t_sec2 is:"+t_sec2+"t_msec2
					// is:"+t_msec2);
					int d = t_sec2 - t_sec1;
					int md = t_msec2 - t_msec1;
					if (d < 0)
						d = d + 60;
					if (md < 0) {
						d = d - 1;
						md = md + 1000;
					}
					if (bSfdzxdz) {
						if (md > 499) {
							md = md - 500;
						} else if (md < 500) {
							d = d - 1;
							md = md + 1000 - 500;
						}
					}
					// tvLog.append("\r\n 读卡时间为: "+d+"."+md+"s");
					// tvLog.append("\r\n 读卡次数："+readCount +"成功次数："+okCount);

					if (bSfdzw) {
						byte[] fingerData = new byte[1024];
						boolean bRet = false;
						try {
							bRet = mClient.GetFingerData(fingerData);
						} catch (IOException e) {
							e.printStackTrace();
						}
						// if(bRet)
						// tvLog.append("\r\n
						// 指纹信息为："+Util.toHexStringNoSpace(fingerData,
						// 1024));
						// else
						// tvLog.append("\r\n 二代证中不包含指纹");
					}
				}
				break;
			case 100:
				// 返回正确照片
				// bm = (Bitmap) msg.obj;
				// iv.setImageBitmap(bm);
				// iv.setVisibility(View.VISIBLE);
				activity.getApplicationContext().deleteFile("zp.bmp");

				break;
			case 101:
				// 返回错误照片原因
				// tvLog.append("\r\n 照片解码授权文件不正确");
				break;
			case 110:
				// 设置是否可以点击按钮读卡
				// btnDk.setEnabled(true);
				break;
			case 102:
				// 返回错误照片原因
				// tvLog.append("\r\n 照片原始数据不正确");
				break;
			case 4:
				// 设置寻卡信息
				// mInfoView.clear();
				// mInfoView.add("正在寻卡...");
				// tvLog.append("\r\n 寻卡失败");
				// iv.setImageBitmap(null);
				// iv.setVisibility(View.GONE);
				break;
			case 5:
				//
				// tvLog.append("\r\n 选卡失败");
				// iv.setImageBitmap(null);
				// iv.setVisibility(View.GONE);
				break;
			case 6:
				//
				// tvLog.append("\r\n 读卡失败");
				if (isConnected) {
				} else {

					closeAndExit();
					initData(activity);
				}
				break;
			case 1:

				break;
			case 7:

				t = Calendar.getInstance();
				t_sec1 = t.get(Calendar.SECOND);
				t_msec1 = t.get(Calendar.MILLISECOND);
				break;
			case 87:

				// tvLog.append("\r\n 读卡初始化中，请稍候...");
				break;
			case 88:

				// tvLog.append("\r\n 机具信息监听中...");
				break;
			case 99:

				break;

			case 222:
				if (isConnected) {
					beginReadCard();
				}
				beginReadCard();
				break;

			case 333:
				String data = (String) msg.obj;
				Log.e("ComShell", data + "******************");
				System.out.println(data + "******************");
				// Toast.makeText(activity, data, 0).show();
				if (data != null) {
					if (listener != null) {
						listener.onIDDataReceived(data);
					}
				}

				break;
			default:
				break;
			}
		}
	};
	private IDCardConnectListener listener;

	public void closeAndExit() {
		bStopReadCard = true;
		iNeedReadCount = 1;
		if (mClient != null) {
			if (isConnectSocket) {
				mClient.disconnectBt();
			}
			if (isConnected) {
				isConnected = false;
			}
			mClient.Destroy();
		}
		mClient = null;
	}

	public static String bytesToString(byte[] b, int length) {
		StringBuffer result = new StringBuffer("");
		for (int i = 0; i < length; i++) {
			result.append((char) (b[i]));
		}

		return result.toString();
	}

	public void removeListener() {
		if (listener != null) {
			listener = null;
		}
	}

	public void setListener(IDCardConnectListener listener) {
		this.listener = listener;
	}

	public interface IDCardConnectListener {
		void onIDCardConnect();

		void onIDDataReceived(String data);
	}

	public void setiNeedReadCount(int iNeedReadCount) {
		this.iNeedReadCount = iNeedReadCount;
	}

	/**
	 * 设置重新返回界面
	 * 
	 * @author 王婷婷
	 * @date 2017年6月8日 下午8:06:18
	 */
	public void setResume() {
		if (mClient != null) {
			readCount = 0;
			new Thread(new GetDataThread()).start();
		}
	}

	/**
	 * 结束扫描
	 * 
	 * @author 王婷婷
	 * @date 2017年6月8日 下午8:08:34
	 */
	public void stopScanReceive() {
		bSflxdk = false;
		bStopReadCard = false;
		iNeedReadCount = 1;
	}

	/**
	 * 开始进行数据的接收
	 * 
	 * @author 王婷婷
	 * @date 2017年6月8日 下午8:09:13
	 */
	public void startScanReceive() {

		bSflxdk = true;
		bStopReadCard = false;
		readCount = 0;
		iNeedReadCount = 100000;
	}
}

